package com.fastbee.web.wnx.service;

import com.alibaba.fastjson.JSONArray;
import com.fastbee.common.utils.uuid.IdUtils;
import com.fastbee.web.wnx.GetWnxApiData;
import com.fastbee.web.wnx.entity.PurchaseMaterial;
import com.fastbee.web.wnx.entity.PurchaseReturn;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class PurchaseReturnService {


    private static final Logger log = LoggerFactory.getLogger(PurchaseReturnService.class);
    @Autowired
    private DatabaseMetaService databaseMetaService;


    /**
     * 产品合格率
     */
    public void loadPurchaseReturn(Date date) {
        Integer apiCode=146;
        long timestamp = System.currentTimeMillis() / 1000;
        String dateAt = DateFormatUtils.format(date, "yyyy-MM-dd");
        String monthAt = DateFormatUtils.format(date, "yyyy-MM");
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("queryid", apiCode.toString());
        paraMap.put("DATEAT", dateAt);
        String token = GetWnxApiData.generateToken(timestamp,paraMap);
        String jsonInputString =  String.format("{\"DATEAT\":\"%s\",\"timestamp\":%d,\"token\":\"%s\"}", dateAt ,timestamp, token);
        System.out.println("发送数据:"+jsonInputString);
        List<PurchaseReturn> list = new ArrayList<>();
        getWnxApiData(apiCode,jsonInputString,list);
        if(databaseMetaService.testDataSourceConnection("secondary")){
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("date_at",dateAt);
            databaseMetaService.deleteByCondition("secondary","szh_purchase_return",conditions);
            for(PurchaseReturn purchaseReturn:list){
                String insertSql = PurchaseReturn.insertSql();
                Long secondary = databaseMetaService.insertAndReturnKey("secondary", insertSql,
                        IdUtils.simpleUUID(),
                        purchaseReturn.getOrderNo(),purchaseReturn.getDateAt(),
                        purchaseReturn.getReturnReason(),purchaseReturn.getWarehouse(),
                        purchaseReturn.getUUserSign(),monthAt,purchaseReturn.getQuantity()
                        );
                if(secondary==null){
                    log.error("新增失败");
                }
            }
        }
    }

    public Boolean getWnxApiData(Integer apiCode, String jsonData, List<PurchaseReturn> list)  {
        try {
            String response = GetWnxApiData.sendPostRequestFixed("/api/squeryc/" + apiCode, jsonData);
            System.out.println("采购物料"+response);
            if(response.startsWith("{\"Code\":")){
                return false;
            }else if(response.equals("[]")){
                return false;
            }else{
                list.addAll(JSONArray.parseArray(response, PurchaseReturn.class));
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
